__author__ = 'yongtao.wang@gmail.com'

import os
import cgi
import logging

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images

import orzzingmodel
import mokomodel
import spider
import moko
import utility

# Set to true if we want to have our webapp print stack traces, etc
        
class IndexPage(utility.BaseRequestHandler):
    
    def get(self):
        lists = orzzingmodel.orzzing.get_latest_orzzing()
        self.generate('index.html', {
                        'lists': lists,
                     })
        
class orzzingPage(utility.BaseRequestHandler):
    
    _OUTPUT_TYPES = {
    'default': ['text/html', 'html'],
    'html': ['text/html', 'html'],
    'atom': ['application/atom+xml', 'xml'],}
    
    def get(self, orzzingkey):
        orzzingitem = orzzingmodel.orzzing.get(orzzingkey)
        if not orzzingitem:
            self.error(403)
            return

        #output_name = self.request.get('output')
        #if output_name not in orzzingPage._OUTPUT_TYPES:
        #    output_name = 'default'
        #output = orzzingPage._OUTPUT_TYPES[output_name]
        list = orzzingmodel.comment.get_orzzing_comments(orzzingitem)
        self.generate('orzzing.html', {
                      'orzzing': orzzingitem,
                      'comments': list,
                     })
class PostPage(utility.BaseRequestHandler):
    
    def get(self):
        #it maybe pass an url parameter to post content
        #optional parameter:
        #url:
        #title:
        #a = yongtao.wang@gmail.com
        url = self.request.get('url')
        title = self.request.get('title')
        a = self.request.get('a')
        content = None
        if url:
            content = 'hello,world'
        
        self.generate('post.html', {
                'title' : title,
                'source': url,
                'a' : a,
                'content' : content,
                })        
        
class orzzingPostActionPage(utility.BaseRequestHandler):
    
    def post(self):
        title = cgi.escape(self.request.get('title'))
        content = cgi.escape(self.request.get('content'))
        logging.info('user input: title = %s' % title)
        logging.info('user input: content = %s' % content)
        
        orzzing = orzzingmodel.orzzing(title = title, author = users.get_current_user(), content = db.Text(content), reviewed = True)
        orzzing.put()
        
        if self.request.get('next'):
            self.redirect(self.request.get('next'))
        else:
            self.redirect('/')
            
class CommentPostActionPage(utility.BaseRequestHandler):
    def post(self):
        title = cgi.escape(self.request.get('title'))
        content = cgi.escape(self.request.get('content'))
        key = self.request.get('orzzing')
        orzzing = orzzingmodel.orzzing.get(key)
        logging.info('orzzing : %s' % orzzing)
        if not orzzing:
            self.error(403)
            return
        
        comment = orzzingmodel.comment(author=users.get_current_user(), ip=self.request.remote_addr, title = title, content = db.Text(content))
        comment.put()
        
        logging.info('added comments: %s' % comment)
        oc = orzzingmodel.orzzingComments(orzzing = orzzing, comment = comment)
        oc.put()
        
        logging.info('orzzing comment: %s' % oc)
        
        if self.request.get('next'):
            self.redirect(self.request.get('next'))
        else:
            self.redirect('/')

class VotePage(utility.BaseRequestHandler):
    
    def get(self):
        key = self.request.get('id')
        orzzing = orzzingmodel.orzzing.get(key)
        if not orzzing:
            self.error(403)
            return 
        
        vote = int(self.request.get('v'))
        likeit = False
        if vote > 0:
            likeit = True
        user = users.get_current_user()
        next = '/orzzing/%s'%str(orzzing.key())
        if user:
            if orzzingmodel.poke.is_currentuser_voted(orzzing):
                self.redirect(next)
            else:
                poke = orzzingmodel.poke(user= user, ip=self.request.remote_addr, orzzing = orzzing, likeit = likeit)
                poke.put()
                orzzing.update_poke_status(likeit)
        else:
            poke = orzzingmodel.poke(orzzing=orzzing, likeit = likeit)
            poke.put()
            orzzing.update_poke_status(likeit)
        
        self.redirect(next) 
        
class SpiderPage(utility.BaseRequestHandler):
    def get(self):
        s = spider.spider()
        s.crawler('http://www.moko.cc', mokomodel.model, False)
        self.response.out.write('<ol>')
        result = mokomodel.model.all()
        for m in result:
            self.response.out.write('<li> model : <a href="%(url)s">%(name)s</a></li>'%{'url':m.homepage, 'name':m.username})
        self.response.out.write('</ol>')

class CrawlerPage(utility.BaseRequestHandler):
    def get(self):
        entryurl = self.request.get('url')
        if not entryurl:
            entryurl = u'http://www.moko.cc'
        s = spider.spider()
        s.crawler(entryurl, mokomodel.model, True)
        
class DomParsePage(utility.BaseRequestHandler):
    def get(self):
        modelname = self.request.get('name')
        if modelname:
            m = spider.test_parse_dom(modelname)
            self.generate('domtest.html', {'model': m,})
            return
        self.error(404)

class ImagePage(webapp.RequestHandler):
    def get(self, imagekey):
        if imagekey:
            r = mokomodel.rawphotodata.get_rawphoto(imagekey)
            if not r:
                logging.error('not found specified photo in datastore:%s'%imagekey)
                self.error(404)
            else:
                i = images.Image(r.rawdata)
                blob = images.resize(r.rawdata, width=i.width, height=i.height)
                self.response.headers['Content-Type'] = 'image/png'
                self.response.out.write(blob)
            
class MOKOImgPage(webapp.RequestHandler):
    def get(self, imagekey):
        if imagekey:
            logging.debug('image key:%s'%imagekey)
            r = mokomodel.rawphotodata.get_rawphoto(imagekey)
            blob = None
            if not r:
                blob = spider.fetch_photo(imagekey)
            else:
                blob = r.rawdata
            
            i = images.Image(blob)
            if blob:
                blob = images.resize(blob, width=i.width, height=i.height)
                self.response.headers['Content-Type'] = 'image/png'
                self.response.out.write(blob)
            else:
                logging.debug('image data is empty')
                self.error(404)

application = webapp.WSGIApplication([
            ('/', IndexPage),
            ('/post.*', PostPage),
            (r'/orzzing/(.*)', orzzingPage),
            ('/commentaction.do', CommentPostActionPage),
            ('/vote', VotePage),
            ('/spider.*', SpiderPage),
            ('/domtest.*', DomParsePage),
            ('/crawler.*', CrawlerPage),
            (r'/img/(.*)', ImagePage),
            (r'/imgmoko/(.*)', MOKOImgPage),
            ('/postaction.do', orzzingPostActionPage)], debug=utility.DEBUG)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
